#include "loadingthread.h"
#include <QDebug>
#include <QTimer>
#include "libvcard/vcard.h"

LoadingThread::LoadingThread(QMobex *phoneDevie)
{
    phone = phoneDevie;//Mobex phone
    counter = 0;//use for looping
    running = false;
    qDebug("Creating thread");
    contactsTable = 0;
}
LoadingThread::~LoadingThread() {
    phone = 0;
    qDebug("Destroyed Loading Thread");
}
bool LoadingThread::isRunning() {
    return running;
}

void LoadingThread::load(vCardHash *table, QByteArray fromMem) {
    contactsTable = table;
    from = fromMem;
    running = false;
    totalContacts = 0;
    counter = 0;
}
void LoadingThread::run() {
    running = true;//start event
    qDebug("Starting thread....");
      currentContacts = 0;
    if(!phone->contactsCount(currentContacts,totalContacts, from)) {
        running = false;
        return;
    }
    emit total(currentContacts);;
    qDebug("Found contacts %d", currentContacts);
    contactsTable->clear();
    QHash<int,QByteArray> responsData;
    while(running) {
        responsData.clear();
        QByteArray response = phone->contactsLoad(responsData, counter, from);
        QHashIterator<int, QByteArray> iter(responsData);
        while(iter.hasNext()) {
            iter.next();
            int id = iter.key();
            vCard card = vCard::fromByteArray(iter.value()).at(0);
            contactsTable->insert(id,card);
            emit parsed(contactsTable->size());
        }
        if(response == QMobex::PARAMS_NEXT) {//loop to next part
            ++counter;
        }
        else {
            running = false;
            this->quit();
        }
    }
}
void LoadingThread::stop() {
    counter = 0;
    running = false;
    this->quit();
}


